﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Leuphana.GuidedTour.App.ViewModels;
using System.Windows.Media.Imaging;

namespace Leuphana.GuidedTour.App.Pages
{
    public partial class SliderPage : PhoneApplicationPage
    {
        private ArticleViewModel _viewModel;
        private int _currentImage = 0;
        
        public SliderPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Page is new, get article ID from query string
            if (e.NavigationMode == NavigationMode.New)
            {
                // Get id from query string
                var id = NavigationContext.QueryString["id"] as String;

                // Create new view model
                _viewModel = new ArticleViewModel();
                _viewModel.LoadData(Int32.Parse(id));
            }

            // Page was tombstoned, get article ID from state
            else if (_viewModel == null)
            {
                _viewModel = new ArticleViewModel();

                object id;
                if (State.TryGetValue("id", out id))
                {
                    _viewModel.LoadData((int)id);
                }
            }

            // Update datacontext
            DataContext = _viewModel;

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            // Save HotSpot ID to state.
            State["id"] = _viewModel.ID;
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (_viewModel != null)
            { 
                // Get images as array
                var images = _viewModel.Images.ToArray();

                double stepping = 100d / (double)(images.Count());
                int step = 0;

                while (e.NewValue >= (step + 1) * stepping && step < images.Count() - 1) step++;

                // Update the image
                if (step != _currentImage)
                {
                    _currentImage = Math.Max(0, step);
                    var image = new BitmapImage(new Uri(images[_currentImage], UriKind.Relative));
                    SliderImage.Source = image;
                }
            }
        }
    }
}